# coding=utf8
from pyjvm.runtime.heap import Heap


class StringPool(object):
    __pool = {}

    @staticmethod
    def new(loader, py_string: str):
        interned_strings = StringPool.__pool
        if py_string in interned_strings:
            return interned_strings[py_string]

        utf16_string = py_string.encode('u16')
        u_str = utf16_string.decode('u16')
        data = list(map(ord, u_str))
        j_chars = Heap.new_from_data(loader.load_class('[C'), data)
        j_chars.extra = u_str

        j_string = Heap.new_object(loader.load_class('java/lang/String'))
        j_string.put_field_value('value', '[C', j_chars)

        interned_strings[u_str] = j_string
        return j_string

    @staticmethod
    def intern(j_string):
        u_str = StringPool.to_py_str(j_string)
        if u_str in StringPool.__pool:
            return StringPool.__pool[u_str]
        StringPool.__pool[u_str] = j_string
        return j_string

    @staticmethod
    def to_py_str(j_string) -> str:
        value = j_string.get_field_value('value', '[C')
        u_str = value.extra
        if u_str is None:
            u_str = u''.join(map(chr, value.data))
            j_string.extra = u_str
        return u_str


__all__ = ['StringPool']
